package server

import (
	"data_service/models"
	"time"
)

// AdminService 提供后台管理相关业务逻辑
// 供 handler 层调用，解耦 handler 与 models
// 只负责业务流程，不直接操作数据库

type AdminService struct{}

func NewAdminService() *AdminService {
	return &AdminService{}
}

// GetAllUsers 获取所有用户列表（分页）
func (s *AdminService) GetAllUsers(page, pageSize int) ([]models.User, int64, error) {
	var users []models.User
	var total int64
	models.GetDB().Model(&models.User{}).Count(&total)
	models.GetDB().Limit(pageSize).Offset((page - 1) * pageSize).Find(&users)
	return users, total, nil
}

// UpdateUser 更新指定用户信息
func (s *AdminService) UpdateUser(userId string, name, email, role, status string) (*models.User, error) {
	var user models.User
	if models.GetDB().First(&user, userId).Error != nil {
		return nil, nil
	}
	user.Name = name
	user.Email = email
	user.Role = role
	user.Status = status
	if err := models.GetDB().Save(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

// DeleteUser 删除指定用户
func (s *AdminService) DeleteUser(userId string) error {
	return models.GetDB().Delete(&models.User{}, userId).Error
}

// GetAllPostsAdmin 获取所有动态列表
func (s *AdminService) GetAllPostsAdmin() ([]models.Post, error) {
	var posts []models.Post
	if err := models.GetDB().Preload("User").Find(&posts).Error; err != nil {
		return nil, err
	}
	return posts, nil
}

// UpdatePostAdmin 更新指定动态
func (s *AdminService) UpdatePostAdmin(postId string, post *models.Post) (*models.Post, error) {
	if models.GetDB().First(post, postId).Error != nil {
		return nil, nil
	}
	if err := models.GetDB().Save(post).Error; err != nil {
		return nil, err
	}
	return post, nil
}

// DeletePostAdmin 删除指定动态
func (s *AdminService) DeletePostAdmin(postId string) error {
	return models.GetDB().Delete(&models.Post{}, postId).Error
}

// GetSystemStats 获取系统统计信息
func (s *AdminService) GetSystemStats() (map[string]interface{}, error) {
	var userStats struct {
		Total      int64
		Active     int64
		Banned     int64
		NewLast24h int64
	}
	var postStats struct {
		Total      int64
		NewLast24h int64
	}
	models.GetDB().Model(&models.User{}).Count(&userStats.Total)
	models.GetDB().Model(&models.User{}).Where("status = ?", "active").Count(&userStats.Active)
	models.GetDB().Model(&models.User{}).Where("status = ?", "banned").Count(&userStats.Banned)
	models.GetDB().Model(&models.User{}).Where("created_at >= ?", time.Now().Add(-24*time.Hour)).Count(&userStats.NewLast24h)
	models.GetDB().Model(&models.Post{}).Count(&postStats.Total)
	models.GetDB().Model(&models.Post{}).Where("created_at >= ?", time.Now().Add(-24*time.Hour)).Count(&postStats.NewLast24h)
	return map[string]interface{}{
		"user_stats": userStats,
		"post_stats": postStats,
	}, nil
}
